App({
  globalData: {
    userInfo: null,
  },

  onLaunch() {
    console.log('网事通小程序启动')
  },

  getLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.globalData.location.latitude = res.latitude
        this.globalData.location.longitude = res.longitude
        this.reverseGeocoder(res.latitude, res.longitude)
      },
      fail: () => {
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        })
      }
    })
  },

  reverseGeocoder(latitude, longitude) {
    wx.request({
      url: `${this.globalData.apiBase}/location/reverse`,
      method: 'GET',
      data: {
        latitude,
        longitude
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.globalData.location.address = res.data.address
        }
      }
    })
  },

  login() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            wx.request({
              url: `${this.globalData.apiBase}/auth/login`,
              method: 'POST',
              data: {
                code: res.code
              },
              success: (response) => {
                if (response.statusCode === 200) {
                  const { token, user } = response.data
                  this.globalData.hasLogin = true
                  this.globalData.userInfo = user
                  wx.setStorageSync('token', token)
                  wx.setStorageSync('userInfo', user)
                  resolve(response.data)
                } else {
                  reject(response.data)
                }
              },
              fail: reject
            })
          } else {
            reject(res.errMsg)
          }
        },
        fail: reject
      })
    })
  },

  request(options) {
    const token = wx.getStorageSync('token')
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${this.globalData.apiBase}${options.url}`,
        method: options.method || 'GET',
        data: options.data || {},
        header: {
          'Content-Type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : '',
          ...options.header
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else if (res.statusCode === 401) {
            wx.removeStorageSync('token')
            this.globalData.hasLogin = false
            wx.navigateTo({
              url: '/pages/login/login'
            })
            reject(res.data)
          } else {
            reject(res.data)
          }
        },
        fail: reject
      })
    })
  }
})
